<!-- 工作经历弹窗 -->
<template>
  <el-dialog v-model="visible" :title="title" width="70%" @closed="closed">
    <el-form ref="ruleFormRef" :model="form">
      <el-form-item label="项目名字" prop="project_name">
        <el-input v-model="form.project_name" />
      </el-form-item>
      <el-form-item label="起始时间" prop="start_time">
        <el-date-picker v-model="form.start_time" value-format="YYYY-MM" type="month" placeholder="请选择起始月份" />
      </el-form-item>
      <el-form-item label="结束时间" prop="end_time">
        <el-date-picker v-model="form.end_time" value-format="YYYY-MM" type="month" placeholder="请选择结束月份" />
      </el-form-item>
      <el-form-item label="项目简述" prop="project_content">
        <!-- 这里Editor使用v-if 每次弹窗关闭进行一次销毁 -->
        <Editor v-if="visible" v-model:valueHtml="form.project_content" height="300"></Editor>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="confirm">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import Editor from '@/components/Editor/index.vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['confirm', 'update:visible'])

const ruleFormRef = ref()

const mode = ref('add')
const formIndex = ref(-1)

const title = computed(() => {
  const map = {
    add: '添加',
    edit: '编辑'
  }
  return map[mode.value] + '项目经历'
})

let form = ref({
  project_name: '', // 项目名
  start_time: '', // 起始时间
  end_time: '', // 结束时间
  project_content: '' // 项目内容
})

// 重置表单
const resetForm = formEl => {
  if (!formEl) return
  formEl.resetFields()
}

/** 打开弹窗
 * @param {*} dialogMode 弹窗模式 [add|edit] add-添加 edit-编辑
 * @param {*} index form对应原数组的索引
 * @param {*} sourceForm 传入数据
 */
const open = (dialogMode, index, sourceForm) => {
  mode.value = dialogMode
  if (dialogMode === 'edit') {
    formIndex.value = index
    form.value = { ...sourceForm }
  }
  console.log('%c [ open ]-79', 'font-size:13px; background:pink; color:#bf2c9f;', form.value)
  emit('update:visible', true)
}

const confirm = () => {
  form.value.end_time = form.value.start_time && !form.value.end_time ? '至今' : form.value.end_time
  emit('confirm', {
    mode: mode.value,
    formIndex: formIndex.value,
    data: { ...form.value }
  })
  emit('update:visible', false)
}

const closed = () => {
  resetForm(ruleFormRef.value)
  formIndex.value = -1
  emit('update:visible', false)
}

defineExpose({
  open
})
</script>

<style lang="scss" scoped></style>
